package com.xiaoxu.privatechat.controller.common;

import com.xiaoxu.privatechat.util.CpachaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author xiaoxu
 * @description 系统验证码公用控制器
 * @date 2023/2/13
 */
@Controller
@RequestMapping("/cpacha")
public class CpachaController {

    private final Logger log = LoggerFactory.getLogger(CpachaController.class);

    /**
     * @param vcodeLength 验证码长度
     * @param fontSize    文字大小
     * @param width       图片宽度
     * @param height      图片高度
     * @param method      用来调用此方法的名称，以此名称为键，存入到session中
     * @param request     Http请求
     * @param response    Http响应
     * @description 通用验证码生成器
     */
    @RequestMapping(value = "/generate_cpacha", method = RequestMethod.GET)
    public void generateCpacha(
            @RequestParam(name = "vl", defaultValue = "4") Integer vcodeLength,
            @RequestParam(name = "fs", defaultValue = "21") Integer fontSize,
            @RequestParam(name = "w", defaultValue = "98") Integer width,
            @RequestParam(name = "h", defaultValue = "33") Integer height,
            @RequestParam(name = "method", defaultValue = "admin_login") String method,
            HttpServletRequest request,
            HttpServletResponse response) {
        CpachaUtil cpachaUtil = new CpachaUtil(vcodeLength, fontSize, width, height);
        String generatorVCode = cpachaUtil.generatorVCode();
        //将生成的验证码放入session，以供放后面程序的验证使用
        request.getSession().setAttribute(method, generatorVCode);
        log.info("驗證碼成功生成，method=" + method + ",value=" + generatorVCode);
        try {
            ImageIO.write(cpachaUtil.generatorRotateVCodeImage(generatorVCode, true), "gif", response.getOutputStream());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
